package com.pug.aspect.myLog;

import com.pug.aspect.service.LogsServiceImpl;
import com.pug.aspect.vo.Logs;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Author: lqm
 * create: 2022/5/14 11:13
 * Lover: lqx
 *
 * @see
 */
@Component
@Aspect
@Slf4j
public class SaveLogAspect implements Ordered {
    @Autowired
    LogsServiceImpl logsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DefaultRedisScript<Boolean> ipLimiterLuaScript;

    // 定义aop的切入点
    @Pointcut("@annotation(com.pug.annotation.SaveLog)")
    public void cut() {

    }

    // 拦截属于放入执行之前的行为，所以定义@Before通知
    @Around("cut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws IOException {
        try{
            //前置增强
            Long timeBefore=System.currentTimeMillis();
            //执行真正的方法
            MethodSignature signature =(MethodSignature) proceedingJoinPoint.getSignature();//得到签名，就是得到目标对象(方法)
            System.out.println("签名:"+signature);
            Class<? extends MethodSignature> aClass = signature.getClass();
            String[] parameterNames = signature.getParameterNames();
            //打印日志
            logsService.saveLog(new Logs(aClass,timeBefore,parameterNames));
            //真正的方法执行
            Object proceed = proceedingJoinPoint.proceed();
            //日志后置增强
            Long timeAfter=System.currentTimeMillis();
            logsService.saveLog(new Logs(aClass,timeAfter,parameterNames));
            return proceed;
        }catch (Throwable e){
            log.info("打印日志出错！");
        }
        return null;
    }
    @AfterThrowing(value = "cut()",throwing = "ex")
    public void afterThrowing(Throwable ex){
//        MethodSignature signature =(MethodSignature) proceedingJoinPoint.getSignature();//得到签名，就是得到目标对象(方法)

//        System.out.println("签名:"+signature);
//        Class<? extends MethodSignature> aClass = signature.getClass();
//        String[] parameterNames = signature.getParameterNames();
//        //打印日志
//        Long time=System.currentTimeMillis();
//        Logs logs = new Logs(aClass, time, parameterNames);
//        log.info("{}:方法执行出错了！详情看下面！",aClass);
//        logsService.saveLog(logs);
        log.info(String.valueOf(ex));
    }
    @Override
    public int getOrder() {
        return 9;
    }
}
